package com.gr.dmbackend.service.Impl.dormaddmin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gr.dmbackend.mapper.BuildingMapper;
import com.gr.dmbackend.mapper.StudentMapper;
import com.gr.dmbackend.model.Building;
import com.gr.dmbackend.model.Student;
import com.gr.dmbackend.model.User;
import com.gr.dmbackend.service.dormaddmin.GetStudentService;
import com.gr.dmbackend.utils.GetUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GetStudentServiceImpl implements GetStudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private BuildingMapper buildingMapper;

    @Override
    public JSONObject getStudent(int page) {

        JSONObject resp = new JSONObject();

        User user = GetUserUtil.getCurrentUser();
        QueryWrapper<Building> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("addmin_id", user.getUsername());
        List<Building> buildings = buildingMapper.selectList(queryWrapper1);

        IPage<Student> recordIPage = new Page<>(page, 10);
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        for (Building building: buildings) {
            queryWrapper.eq("building", building.getName());
        }
        List<Student> records = studentMapper.selectPage(recordIPage, queryWrapper).getRecords();
        resp.put("records", records);
        resp.put("records_count", studentMapper.selectCount(queryWrapper));

        return resp;
    }
}
